package chat.client;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class ChatClient {

	/**
	 * @param args
	 */

	PrintWriter writer;
	JTextArea text;
	BufferedReader reader;

	public static void main(String[] args) {
		ChatClient client = new ChatClient();
		client.go();
	}

	private void go() {
		JFrame frame = new JFrame();
		JPanel panel = new JPanel();

		text = new JTextArea(15, 50);
		text.setLineWrap(true);
		text.setWrapStyleWord(true);
		text.setEditable(false);
		JScrollPane scroll = new JScrollPane(text);
		
		// set scrollbar only up or down
		scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

		JTextField textSend = new JTextField(50);
		JButton send = new JButton("send");
		send.addActionListener(new SendButtonListener());
		
		panel.setBackground(Color.red);
		panel.add(scroll);
		panel.add(textSend);
		send.setBackground(Color.CYAN);
		panel.add(send);

		getConnecter();

		// use thread to get reader stream and writer stream from server
		Thread streamThread = new Thread(new Message());
		streamThread.start();
		
		frame.getContentPane().add(BorderLayout.CENTER, panel);
		frame.setTitle("My dear.");
		frame.setLocation(500, 200);
		frame.setSize(300, 400);
		frame.setVisible(true);
	}

	private void getConnecter() {
		try {
			Socket socket = new Socket("localhost", 8888);
			InputStreamReader io = new InputStreamReader(
					socket.getInputStream());
			reader = new BufferedReader(io);
			writer = new PrintWriter(socket.getOutputStream());
			System.out.println("network is ok...");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// get input message and send to server
	class SendButtonListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			writer.println(text.getText());
		}
	}

	// accept message from server
	class Message implements Runnable {
		String message;

		@Override
		public void run() {
			try {
				while ((message = reader.readLine()) != null) {
					text.append(message + "\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
